﻿using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Threading;
using AlipaySDK.Dto.Payment;
using AlipaySDK.Helper;
using Common.Logging;
using Newtonsoft.Json;
using OutDbContext;
using Rmq.Center;
using User.Api.BizExtensions;
using User.Api.Helpers;

namespace Out.TaskRunner.RmqWorkers
{
    public class OrderRefundingUnpickupSucceedWorker : IWorker
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(OrderRefundingUnpickupSucceedWorker));

        public void Start(CancellationToken ct)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }

            using (var consumer = new OrderRefundingUnpickupSucceedConsumer())
            {
                consumer.Subscribe((id, count, dt, msg, channel) =>
                {
                    if (msg.OrderType == OrderType.挂号订单)
                    {
                        return ProcessRegOrder(msg.OrderId, channel);
                    }

                    return new ConsumedResult { Ack = true };
                });

                while (true)
                {
                    if (ct.IsCancellationRequested)
                    {
                        break;
                    }

                    Thread.Sleep(50);
                }
            }
        }

        private ConsumedResult ProcessRegOrder(int orderId, WrapperChannel channel)
        {
            OrderSummary order;
            using (var ctx = new GdsfybjyWeiXinEntities())
            {
                order = ctx.ApptOrders.Where(x => x.Id == orderId).
                    Select(x => new OrderSummary()
                    {
                        OrderStatus = x.OrderStatus,
                        PayState = x.PayState,
                        Id = x.Id,
                        WxTransactionId = x.WxTransactionId,
                        OrderNo = x.OrderNo,
                        SumFee = x.SumFee
                    }).FirstOrDefault();
                ;
                if (order == null)
                {
                    return new ConsumedResult
                    {
                        Ack = true
                    };
                }
            }

            // 微信退号退款中
            DataBaseCommandFactory.CreateDatbaseCommand().WeixinRefunding(orderId);
            try
                {
                    WapPayRefundResponse refundResult = WapPayment.WapPayRefund(new WapPayRefundRequest
                    {

                        NotifyUrl = ConfigurationManager.AppSettings["AlipayNotify"] + "Reg/PaySucceed",
                        BatchNo = DateTime.Now.ToString("yyyyMMddhhmmss") + DateTime.Now.Millisecond,
                        RefundDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),
                        BatchNum = "1",
                        DetailData = order.WxTransactionId + "^" + order.SumFee + "^因退号而退款"
                    });
                    if (refundResult.ResultCode == "0" && refundResult.IsSuccess == "T")
                    {
                        // 微信退号退款成功
                        DataBaseCommandFactory.CreateDatbaseCommand()
                            .WeixinRefundSuccess(orderId, order.WxTransactionId);
                        // RMQ 发送用户退费成功通知
                        var msgProducer = new UserMessageProducer();
                        msgProducer.Publish(new UserMessageMsg
                        {
                            Type = UserMessageType.退号成功退费成功通知,
                            OrderId = order.Id
                        });
                    }
                    else
                    {
                        // 微信退号退款失败
                        DataBaseCommandFactory.CreateDatbaseCommand().WeixinRefundError(orderId);
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat("调用第三方支付退款Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                    return new ConsumedResult
                    {
                        Ack = false,
                        Delay = 1000
                    };
                }
            

            return new ConsumedResult
            {
                Ack = true
            };
        }


        public class OrderSummary
        {
            public int OrderStatus { get; set; }
            public string PayState { get; set; }
            public int Id { get; set; }
            public string WxTransactionId { get; set; }
            public string OrderNo { get; set; }
            public decimal? SumFee { get; set; }
        }
    }
}